package com.huawei.spare.part.replace.language;

import java.net.*;

public class GetIp {

    public static void main(String[] args) throws UnknownHostException, SocketException {

        try (final DatagramSocket socket = new DatagramSocket()) {
            socket.connect(InetAddress.getByName("192.168.0.105"), 10002);
            System.out.println(socket.getLocalAddress().getHostAddress());
        }

        try {
            InetAddress ipAddr = InetAddress.getLocalHost();
            System.out.println(ipAddr.getHostAddress());
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(ipAddr);
            for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
                final short networkPrefixLength = address.getNetworkPrefixLength();
                int shft = 0xffffffff << (32 - networkPrefixLength);
                int oct1 = ((byte) ((shft & 0xff000000) >> 24)) & 0xff;
                int oct2 = ((byte) ((shft & 0x00ff0000) >> 16)) & 0xff;
                int oct3 = ((byte) ((shft & 0x0000ff00) >> 8)) & 0xff;
                int oct4 = ((byte) (shft & 0x000000ff)) & 0xff;
                String submask = oct1 + "." + oct2 + "." + oct3 + "." + oct4;
                System.out.println(submask);
            }
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
        }
    }

    private static String intToIP(int ipAddress) {
        String ret = String.format("%d.%d.%d.%d", (ipAddress & 0xff),
                (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff),
                (ipAddress >> 24 & 0xff));

        return ret;
    }
}
